<?php
	require_once($_SERVER['DOCUMENT_ROOT']."/classes/database.class.php");
	require_once($_SERVER['DOCUMENT_ROOT']."/classes/ColorPair.class.php");
	require_once($_SERVER['DOCUMENT_ROOT']."/includes/define.php");
		
	class MatrixColorsShapes{
		var $matrix;
		var $lastPair;
		var $stepsNumber;
		var $actualStep;
		
		public function MatrixColorsShapes(){
			$this->matrix = array();
			$this->lastPair = "";
			$this->actualStep = 1;
			$this->createMatrix();
		}
		
		public function createMatrix(){
			$bd = new Database(MYSQL_DB_HOST,MYSQL_DB_LOGIN,MYSQL_DB_PASSWORD,MYSQL_DB_NAME);
			$bd->connect();
			$array = array();
			$allShapesData = $bd->query('SELECT * FROM shapes;');
			while($shapeData = mysql_fetch_assoc($allShapesData)){
				$allShapes[] = new Shape($shapeData);
			}
			
			$allColorsData = $bd->query('SELECT * FROM colors;');
			while($colorData = mysql_fetch_assoc($allColorsData)){
				$allColors[] = new Color($colorData);
			}
			$allColorPairs = array();
			
			while(!empty($allColors)){
				foreach($allColors as $secondColor){
					if($allColors[0] != $secondColor) $allColorPairs[] = array($allColors[0],$secondColor);
				}
				array_shift($allColors);
			}
			
			$this->stepsNumber = 0;
			foreach($allColorPairs as $pairName){
				foreach($allShapes as $shape){
					$this->matrix[$pairName[0].'-'.$pairName[1]][$shape.''] = new ColorPair($pairName[0],$pairName[1],$shape);
					$this->stepsNumber++;
				}
			}	
		}
		
		public function getMaxPound(){
			$max = 0;
			foreach($this->matrix as $pair => $shapes){
				if($max < count($shapes)) $max = count($shapes);
			}
			return $max;
		}
		
		public function getColorPairsWithMaxPound(){
			$max = $this->getMaxPound();
			$colorPairs = array();
			foreach($this->matrix as $pair => $shapes){
				if($max == count($shapes)) $colorPairs[] = $pair;
			}
			return $colorPairs;
		}
		
		public function getNextColorPair(){
			$tempArray = $this->getColorPairsWithMaxPound();
			do{
				$randPair = $tempArray[array_rand($tempArray)];
				$randShape = array_rand($this->matrix[$randPair]);
			}while($randPair == $this->lastPair);
			
			$this->lastPair = $randPair;
			$colorPair = $this->matrix[$randPair][$randShape];
			unset($this->matrix[$randPair][$randShape]);
			if(count($this->matrix[$randPair]) == 0) unset($this->matrix[$randPair]);
			return $colorPair;
		}
		
		public function debugMatrixList(){
			while(!empty($this->matrix)){
				echo $this->getNextColorPair();
			}	
		}
	}
?>